package cycling.taxi.com.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.SDKInitializer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import cycling.taxi.com.R;
import cycling.taxi.com.base.BaseFragment;
import cycling.taxi.com.base.LoadDataUi;
import cycling.taxi.com.bean.NoticeInfo;
import cycling.taxi.com.bean.ShopInfo;
import cycling.taxi.com.entity.Tips;
import cycling.taxi.com.ui.activity.TipsItem;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;
import cycling.taxi.com.utils.delHTMLTag;
import cycling.taxi.com.zxing.android.Intents;

/**
 * Created by Administrator on 2017/5/4.
 */
public class TipsFrgt extends BaseFragment implements AbsListView.OnScrollListener, AdapterView.OnItemClickListener {

    private ListView mTipsLv;
    private ArrayList<Integer> mList;
    private ArrayList<Tips> datas;
    private ArrayList<Tips> data;

    private RequestQueue queue;
    private View view_more;
    private ProgressBar pb;
    private TextView tvLoad;
    private ListViewAdapter adapter;
    private int lastVisibleIndex;
    private int start, end;
    private int totalCount = 100;
    private int pageCount = 1;
    private int pageNo = 1;

    @Override
    protected View OnInitSuccessView() {
        View view = LayoutInflater.from(this.getContext()).inflate(R.layout.frgt_tips_lv, null);
        queue = Volley.newRequestQueue(this.getContext());

        mList = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            mList.add(i);
        }

        initUI(view);

        initData();


        return view;
    }

    //public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//    View view = LayoutInflater.from(this.getContext()).inflate(R.layout.frgt_tips_lv, null);
//        queue= Volley.newRequestQueue(this.getContext());
//
//        mList = new ArrayList<>();
//        for (int i=0;i<50;i++){
//            mList.add(i);
//        }
//
//        initUI(view);
//
//        initData();
//
//
//        return view;
//}
    private void initData() {
        volleyGet();
        //   mTipsLv.setAdapter(new ListViewAdapter());
    }

    private void initUI(View view) {
        mTipsLv = (ListView) view.findViewById(R.id.tips_lv);
        view_more = LayoutInflater.from(getActivity()).inflate(R.layout.view_more, null);
        //view_more = (View) getLayoutInflater().inflate(R.layout.view_more, null);
        // 进度条
        pb = (ProgressBar) view_more.findViewById(R.id.progressBar);
        // “正在加载...”文本控件
        tvLoad = (TextView) view_more.findViewById(R.id.tv_Load);
        mTipsLv.setOnItemClickListener(this);

    }

    public void volleyGet() {
        String path = Urls.getTips() + "?beanJson=" + SPUtil.getInstance().getData("beanJson").replace(" ", "%20");
        StringRequest request = new StringRequest(path, new Listener<String>() {
            @Override
            public void onResponse(String s) {
                String[] split;
                LogUtil.e("贴士" + s);
                split = s.split("=");
                pageCount = Integer.parseInt(split[0]);
                data = new Gson().fromJson(split[1], new TypeToken<List<Tips>>() {
                }.getType());
                totalCount = Integer.parseInt(split[2]);
                adapter = new ListViewAdapter();
                mTipsLv.setAdapter(adapter);
                mTipsLv.addFooterView(view_more);
                setListeners();
            }
        }, null);
        queue.add(request);
    }

    public void volleyGet2() {
        pageNo++;
        String path = Urls.getTips() + "?pageNo=" + pageNo + "&beanJson=" + SPUtil.getInstance().getData("beanJson").replace(" ", "%20");
        StringRequest request = new StringRequest(path, new Listener<String>() {
            @Override
            public void onResponse(String s) {
                String[] split;
                LogUtil.e("贴士" + s);
                split = s.split("=");
                datas = new Gson().fromJson(split[1], new TypeToken<List<Tips>>() {
                }.getType());
                for (int i = 0; i < datas.size(); i++) {
                    data.add(datas.get(i));

                }

                adapter.notifyDataSetChanged();
            }
        }, null);
        queue.add(request);
    }

    private void setListeners() {
        if (pageCount > 1) {
            // listView设置滑动简监听
            mTipsLv.setOnScrollListener(this);
        } else {
            // 假如数据总数少于等于15条，直接移除底部的加载布局，不需要再加载更多的数据
            mTipsLv.removeFooterView(view_more);
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        Log.e("TAG", "lastVisibleIndex = " + lastVisibleIndex);
        Log.e("TAG", "adapter.getCount() = " + adapter.getCount());
        // 滑到底部后自动加载，判断listView已经停止滚动并且最后可视的条目等于adapter的条目
        // 注意这里在listView设置好adpter后，加了一个底部加载布局。
        // 所以判断条件为：lastVisibleIndex == adapter.getCount()
        if (adapter.getCount() == 0) {
            volleyGet();
        }
        if (scrollState == SCROLL_STATE_IDLE
                && lastVisibleIndex == adapter.getCount()) {
            /**
             * 这里也要设置为可见，是因为当你真正从网络获取数据且获取失败的时候。
             * 我在失败的方法里面，隐藏了底部的加载布局并提示用户加载失败。所以再次监听的时候需要
             * 继续显示隐藏的控件。因为我模拟的获取数据，失败的情况这里不给出。实际中简单的加上几句代码就行了。
             */
            pb.setVisibility(View.VISIBLE);
            tvLoad.setVisibility(View.VISIBLE);
            //  ToastUtil.getInstance().toast("xiala");
            loadMoreData();// 加载更多数据
        }
    }

    private void loadMoreData() {
        // 获取此时adapter中的总条目数
        int count = adapter.getCount();
        // 一次加载15条数据，即下拉加载的执行
        if (pageNo < pageCount) {
            volleyGet2();
            // initData(start, end);// 模拟网络获取数据操作
        }

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// 计算最后可见条目的索引
        lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
        // 当adapter中的所有条目数已经和要加载的数据总条数相等时，则移除底部的View
        if (totalItemCount == totalCount + 1) {
            // 移除底部的加载布局
            Toast.makeText(getActivity(), "数据已经全部加载", Toast.LENGTH_LONG).show();
            mTipsLv.removeFooterView(view_more);

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent tipsItem = new Intent(this.getActivity(), TipsItem.class);
        Adapter adpter = parent.getAdapter();
        Tips item = (Tips) adpter.getItem(position);//拿到当前数据值并强转   adpter.getItem(i)即为当前数据对象
        tipsItem.putExtra("Tip", item);
        tipsItem.setClass(this.getActivity(), TipsItem.class);
        startActivity(tipsItem);
    }

    public class ListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout.lv_tips_item, null);
            }
            Tips tips = data.get(position);

            holder = new ViewHolder();
            holder.tv = (TextView) convertView.findViewById(R.id.tips_tv);
            holder.content = (TextView) convertView.findViewById(R.id.tips_content);
            holder.time = (TextView) convertView.findViewById(R.id.tips_time);
            holder.tv.setText(tips.getTitle());
            holder.content.setText("\u3000\u3000" + delHTMLTag.delHTMLTag(tips.getContent()));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            holder.time.setText(format.format(tips.getCreateTime()));
            convertView.setTag(holder);
            return convertView;
        }
    }

    static class ViewHolder {
        TextView tv;
        TextView content;
        TextView time;
    }

    @Override
    protected LoadDataUi.Result doInbackground() {
        return LoadDataUi.Result.SUCCESS;
    }
}
